package com.sorcery.coupon.service;

import com.sorcery.coupon.dao.PathRepository;
import com.sorcery.coupon.entity.Path;
import com.sorcery.coupon.vo.CreatePathRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 路径相关的服务功能实现
 *
 * @author jinglv
 * @date 2024/4/30 14:04
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PathService {
    /**
     * Path Repository
     */
    private final PathRepository pathRepository;

    /**
     * 添加新的path到数据表中
     *
     * @param createPathRequest {@link CreatePathRequest} 路径创建请求
     * @return Path数据记录的主键
     */
    public List<Integer> createPath(CreatePathRequest createPathRequest) {
        List<CreatePathRequest.PathInfo> pathInfoList = createPathRequest.getPathInfoList();
        List<CreatePathRequest.PathInfo> validRequests = new ArrayList<>(createPathRequest.getPathInfoList().size());
        List<Path> currentPaths = pathRepository.findAllByServiceName(pathInfoList.get(0).getServiceName());
        if (!CollectionUtils.isEmpty(currentPaths)) {
            for (CreatePathRequest.PathInfo pathInfo : pathInfoList) {
                boolean isValid = true;
                for (Path currentPath : currentPaths) {
                    if (currentPath.getPathPattern().equals(pathInfo.getPathPattern()) && currentPath.getHttpMethod().equals(pathInfo.getHttpMethod())) {
                        isValid = false;
                        break;
                    }
                }
                if (isValid) {
                    validRequests.add(pathInfo);
                }
            }
        } else {
            validRequests = pathInfoList;
        }
        List<Path> paths = new ArrayList<>(validRequests.size());
        validRequests.forEach(p -> paths.add(new Path(
                p.getPathPattern(),
                p.getHttpMethod(),
                p.getPathName(),
                p.getServiceName(),
                p.getOpMode()
        )));
        return pathRepository.saveAll(paths).stream().map(Path::getId).collect(Collectors.toList());
    }
}
